/**
 * Unit 
 * Define Unit objects
 **/
var Unit = function() {

	this.color = 'blue';
	this.target = null;
	this.position = null;
	this.selected = false;
	this.lastMove = null;
	this.path = new Path();
	this.bounds = {
		w: 20,
		h: 20
	};

	this.init = function(p) {
		log('*** INIT UNIT ***');
		this.position = p;
		this.target = this.position;
		this.lastMove = +new Date();
	}

	this.clear = function() {
	}

	this.update = function() {
		this.input();

		if (distance(this.target,this.position) != 0 && interval(this.lastMove, 1))
			this.move();
	}

	this.input = function() {
		// input.listen();

		// if (input.mouse.click === true) {
		// 	var newTarget = game.mMap.getPosition({x:input.mouse.x,y:input.mouse.y});
		// 	if (game.mMap.isWalkable(newTarget))
		// 		this.setTarget(newTarget);
		// }
	}

	this.onClick = function() {
		this.color = 'orange';
		this.selected = true;
	}

	this.render = function() {
		// log('*** RENDER UNIT ***');
		if (this.target != null) 
			this.renderTarget();

		var pW = this.getWidth();
		var pH = this.getHeight();
		var pX = this.getDrawX() + (Math.round((game.mMap.getCellWidth() - pW) / 2));
		var pY = this.getDrawY() + (Math.round((game.mMap.getCellHeight() - pH) / 2));

		CTX.beginPath();
		CTX.rect(pX, pY, pW, pH);
		CTX.fillStyle = this.color;
		CTX.fill();
		CTX.closePath();
	}

	this.renderTarget = function() {
		var pW = this.getWidth();
		var pH = this.getHeight();
		var pX = this.target.x * game.mMap.getCellWidth() + (Math.round((game.mMap.getCellWidth() - pW) / 2));
		var pY = this.target.y * game.mMap.getCellHeight() + (Math.round((game.mMap.getCellHeight() - pH) / 2));

		CTX.beginPath();
		CTX.rect(pX, pY, pW, pH);
		CTX.fillStyle = 'red';
		CTX.fill();
		CTX.closePath();
	}

	this.move = function() {
		log('Move');
		this.lastMove = +new Date();
		this.position = this.path.getNextMove(this.position);
	}

	// Access Configuration
	this.getWidth = function() { return this.bounds.w; }
	this.getHeight = function() { return this.bounds.h; }
	this.getDrawX = function() { return this.position.x * game.mMap.getCellWidth(); }
	this.getDrawY = function() { return this.position.y * game.mMap.getCellHeight(); }
	this.getX = function() { return this.position.x; }
	this.getY = function() { return this.position.y; }

	// A* Pathfinding
	this.setTarget = function(t) {
		log('Set Target');
		if (distance(t,this.target) != 0) {
			this.target = t;
			this.path.getPath(this.position, this.target);
		}
	}
};